package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.dto.role.RoleDTO;
import com.qk.entity.Role;
import com.qk.management.mapper.RoleMapper;
import com.qk.management.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 *
 * @author MrZhao
 * @created 2025-10-08 18:30
 * @description 角色管理业务层实现类
 *
 */
@Slf4j
@Service
@SuppressWarnings("all")
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public void updateById(RoleDTO dto) {
        boolean hasNullField = BeanUtil.hasNullField(dto, "remark", "page", "pageSize");
        if (hasNullField) {
            throw new RuntimeException("参数错误");
        }
        Role role = BeanUtil.copyProperties(dto, Role.class);
        role.setUpdateTime(LocalDateTime.now());
        log.info("修改角色：{}", role);
        roleMapper.update(role);
    }

    @Override
    public Role getById(Integer id) {
       return roleMapper.getById(id);
    }

    @Override
    public void add(RoleDTO dto) {
        // 参数校验
        boolean hasNullField = BeanUtil.hasNullField(dto, "remark", "page", "pageSize","id");
        if (hasNullField) {
            throw new RuntimeException("参数错误");
        }
        // 创建实体类,将dto转为实体类
        Role role = BeanUtil.copyProperties(dto, Role.class);
        // 创建时间
        role.setCreateTime(LocalDateTime.now());
        // 修改时间
        role.setUpdateTime(LocalDateTime.now());
        log.info("添加角色：{}", role);
        roleMapper.insert(role);
    }

    @Override
    public void deleteById(Integer id) {
        log.info("删除角色：{}", id);
        roleMapper.deleteById(id);
    }

    @Override
    public PageResult<Role> page(RoleDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<Role> result = roleMapper.selectByPage(dto);
        Page<Role> rs = (Page<Role>) result;
        return PageResult.<Role>builder()
                .total(Long.valueOf(rs.getTotal()).intValue())
                .rows(rs.getResult())
                .build();
    }

    @Override
    public List<Role> list() {
        return roleMapper.selectAll();
    }
}
